import store from '@/store'

/**
 * 字符权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkPermi(value) {
  if (value && value instanceof Array && value.length > 0) {
    const permissions = store.getters && store.getters.permissions
    const permissionDatas = value
    const all_permission = "*:*:*";

    const hasPermission = permissions.some(permission => {
      return all_permission === permission || permissionDatas.includes(permission)
    })

    return hasPermission;

  } else {
    console.error(`need roles! Like checkPermi="['system:user:add','system:user:edit']"`)
    return false
  }
}

/**
 * 角色权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkRole(value) {
  if (value && value instanceof Array && value.length > 0) {
    const roles = store.getters && store.getters.roles
    const permissionRoles = value
    const super_admin = "admin";

    const hasRole = roles.some(role => {
      return super_admin === role || permissionRoles.includes(role)
    })

    return hasRole;

  } else {
    console.error(`need roles! Like checkRole="['admin','editor']"`)
    return false
  }
}

/**
 * 路由权限校验 
 * @param {Array} userRouter 后台获取的路由
 * @param {Array} allRouter 前端配置的路由
 * @returns {Array} realRouters 过滤之后，符合条件的路由
 */
export function recursionRouter(userRouter = [], allRouter = []) {
  var realRouters = []

  allRouter.forEach((v, i) => {
    userRouter.forEach((item, index) => {
      if(item.meta.title === v.meta.title) {
        if(item.children && item.childrenlength > 0) {
          v.children = recursionRouter(item.children, v.children)
        }
        realRouters.push(v)
      }
    })
  })

  return realRouters
}

/**
 * 指定返回的默认路由
 * @param {Array} allRouter 前端配置的路由
 * @returns {Array} realRouters 过滤之后，符合条件的路由
 */
export function setDefaultRouts (routes) {
  routes.forEach((v, i) => {
    if(v.children && v.children.length > 0) {
      v.redirect = {name: caches.children[0].name}
      setDefaultRouts(v.children)
    }
  })
}